from datetime import timedelta
import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from tables import *
from utility import Util

def out(self, s):
    self.response.out.write(s + "<br/>")

def getKnowldgeBase(type):
        diseasesQry = AreaDisease.all().filter("diagType =",type).order('-weight').fetch(1000)
	diseases = []
        for part in diseasesQry:
            part.id = part.key().id()
	    part.symptomParts=DiseaseSymptom.all().filter('disease_name =',part.disease_name)
            diseases.append(part)
	return diseases

def getAlldiseases(diagType):
    m = db.GqlQuery("SELECT * FROM AreaDisease order by weight desc")
    list = []
    for dis in m:
        if dis.diagType == diagType:
            list.append(dis)
    return list

def getSymptoms(disease):
    m = db.GqlQuery("SELECT * FROM DiseaseSymptom")
    list = []
    for dis in m:
        if dis.disease_name.find(disease) >= 0:
            list.append(dis.symptom)
    return list

def hasForbidden(symps, rejected):
    for sym in symps:
        if sym in rejected:
            return True
    return False

def allAccepted(symps, accepted):
    #print "checking if all "+str(symps)+" are in "+str(accepted)
    for sym in symps:
        if sym not in accepted:
            return False
    return True

def notYetAccepted(symps, accepted):
    for sym in symps:
        if sym not in accepted:
            return sym
    return "" #this is an unreachable statement

def toString(array):
    str = ""
    for s in array:
        str = str + s + ","
    return str[:-1]


class DataCreator(webapp.RequestHandler):
    def get(self):
        createData()
        self.response.out.write("data created")
        
class LoginHandler(webapp.RequestHandler):
    def get(self):
        logins = Util.getLoginDetails()
        Login(email=logins['email']).put()
        self.redirect("/")
class DiagTypesHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write("plants----Plants::::windows computers----Windows computers::::human----Human::::animals----Animals::::")

class SaveDisease(webapp.RequestHandler):
    def post(self):            
        AreaDisease(disease_name=self.request.get('disease_name'),
                    prevention=self.request.get('prevention'), diagType=self.request.get('diagType'),
                    weight=int(self.request.get('weight'))).put()
        
        symptoms = self.request.get('symptoms').rsplit(",")
        for symp in symptoms:
            if symp:
                DiseaseSymptom(disease_name = self.request.get('disease_name'),symptom = symp).put()
        self.redirect('/')

class NewClient(webapp.RequestHandler):
    def get(self):
        newid = Session(rejected="", accepted="", diagType=self.request.get('diagType', 'plants')).put().id()
        self.response.out.write(newid)

class Diagnosis(webapp.RequestHandler):
    def get(self):
        session_id = self.request.get('id')
        answer = self.request.get('answer')
        symp = self.request.get('symptom')
        if session_id:
            ob = Session.get_by_id(int(session_id))
            accepted = ob.accepted
            rejected = ob.rejected
            diagType = ob.diagType
            if accepted:
                accepted = accepted.rsplit(",")
            else:
                accepted = []
            if rejected:
                rejected = rejected.rsplit(",")
            else:
                rejected = []
            if len(answer) > 0:
                if answer == 'yes':
                    accepted.append(symp)
                if answer == 'no':
                    rejected.append(symp)
            di = getAlldiseases(diagType)
            stop = False
            diagnosis = ""
            for dis in di:
                if stop:
                    break
                sy = getSymptoms(dis.disease_name)
                #out("dealing with " + di[k] + " whose symptoms are " + toString(sy));
                while (True):
                    if stop:
                        break
                    if hasForbidden(sy, rejected):
                        break
                    elif allAccepted(sy, accepted):
                        #print "allAccepted(sy,accepted)="+str(allAccepted(sy,accepted))
                        self.response.out.write("found: " + dis.disease_name + ": " + dis.prevention)
                        diagnosis = dis.disease_name + ": " + dis.prevention
                        dis.weight = dis.weight + 1
                        dis.put()
                        stop = True
                    else:
                        te = notYetAccepted(sy, accepted);
                        self.response.out.write(te)
                        stop = True
	    accepted = toString(accepted)
	    rejected = toString(rejected)
            if not stop:#no diagnnosis made after trying all diseases
                self.response.out.write("end")
                ob.diagnosis = "Diagnosis not possible with the current data. Pls contact a professional."
	    else: # either nade a diagnosis all still asking for symptoms
                ob.diagnosis = diagnosis
	    ob.accepted = accepted
	    ob.rejected = rejected
	    ob.put()
		    
		
        else:
            self.response.out.write("No Session ID given")

class ServeComments(webapp.RequestHandler):
    def get(self):
        comments = Comment.all().order('-date').fetch(30)
        for comment in comments:
            self.response.out.write(Util.handleTimeDetailed(comment.date) + ' : <b>%s</b>:' % comment.author + '<blockquote>' + comment.content + '</blockquote> <hr/>')

class CommentHandler(webapp.RequestHandler):
    def post(self):
        username = Util.getCurrentUser()
        if not username:
            username = "Anonymous"
        Comment(content=self.request.get('content'), email=self.request.get('email'), author=username).put()
        self.redirect('/')

class RefreshCommentHandler(webapp.RequestHandler):
    def get(self):
        username = Util.getCurrentUser()
        if not username:
            username = "Anonymous"
        Comment(content=self.request.get('content'), email=self.request.get('email'), author=username).put()
        self.redirect('/serv_com')

class MainHandler(webapp.RequestHandler):
    def get(self):
        logins = Util.getLoginDetails();
        comments = Comment.all().order('-date').fetch(1000)
        commentsArr = []
        for comment in comments:
            comment.date1 = Util.handleTimeDetailed(comment.date)
            commentsArr.append(comment)

        sessionParts = Session.all().order('-date').fetch(10)
        sessions = []
        for part in sessionParts:
            part.id = part.key().id()
            part.date1 = Util.handleTimeDetailed(part.date)
            sessions.append(part)
	knowledge={}
	knowledge['plants']=getKnowldgeBase('plants')
	knowledge['windows']=getKnowldgeBase('windows computers')
	knowledge['human']=getKnowldgeBase('human')
	knowledge['animals']=getKnowldgeBase('animals')
        template_values = {
            'sessionParts': sessions,
            'knowledge': knowledge,
            'comments': commentsArr,
            'logins': logins
            }
        #self.response.headers['Location'] = urllib.quote(absolute_url.encode("utf-8"))
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))
        
def main():

    application = webapp.WSGIApplication([('/', MainHandler),
                                         ('/new', NewClient),
                                         ('/login', LoginHandler),
                                         ('/diag_types', DiagTypesHandler),
                                         ('/diagnosis', Diagnosis),
                                         ('/createdata', DataCreator),
                                         ('/comm', CommentHandler),
                                         ('/refresh_com', RefreshCommentHandler),
                                         ('/serv_com', ServeComments),
                                         ('/save_dis', SaveDisease)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
